package business
{
	public class TreeManager
	{
		public function TreeManager()
		{
			trace('Create TreeManager...');
		}
		
		
		private var _tree:XML;
	
		[Bindable]
		public function get tree():XML
		{
			return _tree;
		}
		
		public function set tree(tree:XML):void
		{
			//if(_tree == null)
			//{
			trace('tree loaded', tree);
				_tree = tree;
				//return;
			//}
			
			//mergeTrees(_tree, tree);	
		}
		
		private function mergeTrees(_tree:XML, tree:XML):void
		{			
			var ch1:XMLList = _tree.children();
			var ch2:XMLList = tree.children();
			var i:Number;
			
			//Delete Unnecessari Nodes
			for( i = ch1.length() - 1; i >= 0; i--)
			{
				if( !ch2.contains(ch1[i]) ){
					delete _tree.children()[i];
				}
			}
			
			//Insert Relevant Nodes
			for( i = 0; i < ch2.length(); i++)
			{
				if( !ch1.contains(ch2[i]) ){
					(ch1[i] == null) ? 
						_tree.appendChild(ch2[i]) : 
						_tree.insertChildBefore( ch1[i], ch2[i] );
				}
			}
		
		
		
			
		}
		
		public function addNode(nodeName:String, set:XML):Boolean
		{
			var hozzaadas:Boolean = false;
			if(nodeName != ""){
				var newNode:XML = <n/>;
				newNode.@label = nodeName;
				set.appendChild(newNode);
				hozzaadas = true;
			}
			return hozzaadas;
		}
		
		public function deleteNode(nodeToDelete:XML):Boolean
		{
			var rv:Boolean = false;
			if(nodeToDelete != null){
				var cn:XMLList = XMLList(nodeToDelete.parent()).children();
				
				for (var i:Number = 0; i < cn.length(); i++) {
					if (cn[i] == nodeToDelete) {
						delete cn[i];
						rv = true;
					}
				}
			}
			return rv;	
		}
		
		public function compareNodes( tree:XML):Boolean
		{
			if(_tree != null && tree != null){
				return (_tree.* == tree.*);
			}
			return false;
		}
	}
}